<template>
  <view class="search">
    <view class="search__box">
      <!-- mSearch组件 如果使用原样式，删除组件元素-->
      <search-input
        class="search__input"
        button="inside"
        v-model="keyword"
        :mode="2"
        :placeholder="defaultKeyword"
        :input-focus="inputFocus"
        placeholder-class="search__input-placeholder"
        @search="handleInputConfirm(false)"
        @confirm="handleInputConfirm(false)"
      />
    </view>
    <view class="search__keyword" @touchstart="blur">
      <scroll-view
        class="search__keyword-list"
        v-show="showSearchResult"
        scroll-y
        :scroll-top="scrollTop"
        @scrolltolower="handleLoadMore"
      >
        <!-- 分类数据 -->
        <navigator
          v-for="(book, index) in searchResult"
          :key="book._id"
          :url="book._id ? `/pages/bookdetail/index?id=${book._id}` : ''"
          :class="{ search__item: true, opacity: !book }"
          hover-class="none"
        >
          <skeleton
            title
            animate
            :row="3"
            :loading="loading"
            comp-style="display: flex;flex-flow: row nowrap;justify-content: flex-start;align-items: center;position: relative;"
          >
            <!-- #ifdef H5 -->
            <view class="search__item-info">
              <view
                class="search__name"
                v-html="drawCorrelativeKeyword(book.name)"
              />
              <view class="search__des">{{ book.des }}</view>
              <view class="search__bottom">
                <text v-html="drawCorrelativeKeyword(book.author)">{{
                  book.author
                }}</text>
              </view>
            </view>
            <!-- #endif -->
            <!-- #ifndef H5 -->
            <view class="search__item-info">
              <view class="search__name">{{ book.name }}</view>
              <view class="search__des">{{ book.des }}</view>
              <view class="search__bottom">
                <text>{{ book.author }}</text>
              </view>
            </view>
            <!-- #endif -->
            <LazyLoadImg
              :index="index"
              class="search__img"
              threshold="0"
              width="75"
              height="109"
              img-mode="aspectFit"
              :image="book.img_url"
            />
          </skeleton>
        </navigator>
        <!-- 数据为空 -->
        <NoData
          v-if="!loading && total === 0"
          text="未找到你要的书籍, 试试换个关键字"
          comp-style="margin-top: 120rpx"
        >
          <text class="iconfont icon-emptypage" />
        </NoData>
        <!-- 正在加载更多 -->
        <view v-if="hasMore && loadingMore" class="search__load-more">
          <LoadingInline
            text="更多书籍正在加载中..."
            color="#666"
            :wrap="false"
          />
        </view>
        <!-- 已经没有更多了 -->
        <view v-if="!hasMore && total > 0" class="search__no-more">
          已经到底了~
        </view>
        <!-- 返回顶部 -->
        <div v-if="showBackTop" class="search__backtop">
          <text class="iconfont icon-backtotop" @click="goBackTop" />
        </div>
      </scroll-view>
      <scroll-view
        class="search__keyword-box"
        v-show="!showSearchResult"
        scroll-y
      >
        <!-- 历史搜索 -->
        <History :datas="oldKeywordList" @select="handleSelectHistory" />
        <!-- 热门搜索 -->
        <HotSearch />
      </scroll-view>
    </view>
  </view>
</template>

<script>
import { mapGetters } from 'vuex';
import { get } from '@/utils';
import { platformName } from '@/config';
import SearchInput from '@/components/SearchInput';
import LazyLoadImg from '@/components/LazyLoadImg2';
import LoadingInline from '@/components/LoadingInline';
import NoData from '@/components/NoData';
import HotSearch from './components/HotSearch';
import History from './components/History';

export default {
  data() {
    return {
      defaultKeyword: '',
      keyword: '',
      oldKeywordList: [],
      hotSearchList: [],
      searchResult: [],
      showSearchResult: false,
      loading: true,
      loadingMore: false,
      page: 1,
      total: 0,
      inputFocus: false,
      showBackTop: false,
      scrollTop: 0,
    };
  },

  onLoad() {
    this.loadDefaultKeyword();
    this.loadOldKeyword();
  },

  components: {
    SearchInput,
    HotSearch,
    History,
    LazyLoadImg,
    LoadingInline,
    NoData,
  },

  computed: {
    ...mapGetters(['settings']),
    isOpenHideMode() {
      return (
        get(this.settings, 'is_open_hide_mode', false) &&
        platformName === 'mp-weixin'
      );
    },
    hasMore() {
      return this.total > this.page * 8;
    },
  },

  watch: {
    keyword(newValue) {
      if (this.searchRequestTimer) {
        clearTimeout(this.searchRequestTimer);
      }
      this.searchRequestTimer = setTimeout(() => {
        this.fetchBook(true);
      }, 500);
    },
  },

  methods: {
    blur() {
      uni.hideKeyboard();
      // 保存搜索历史
      this.saveKeyword(this.keyword);
    },

    // 加载默认搜索关键字
    loadDefaultKeyword() {
      // 定义默认搜索关键字，可以自己实现ajax请求数据再赋值,用户未输入时，以水印方式显示在输入框，直接不输入内容搜索会搜索默认关键字
      this.defaultKeyword = '请输入书名或者作者名';
    },

    // 加载历史搜索,自动读取本地Storage
    loadOldKeyword() {
      uni.getStorage({
        key: 'OldKeys',
        success: (res) => {
          const OldKeys = JSON.parse(res.data);
          this.oldKeywordList = OldKeys;
        },
      });
    },

    // 处理输入
    fetchBook(init = false) {
      if (init) {
        this.page = 1;
        this.total = 0;

        // 兼容引入组件时传入参数情况
        if (!this.keyword) {
          this.searchResult = [];
          this.showSearchResult = false;
          return;
        }

        this.showSearchResult = true;
        this.loading = true;
        this.showBackTop = false;
      } else {
        this.loadingMore = true;
        this.page += 1;
      }

      this.$http({
        method: 'POST',
        url: '/api/front/book/search',
        data: { keyword: this.keyword, page: this.page },
        needAuth: false,
        skipToast: true,
      })
        .then((res) => {
          if (this.isOpenHideMode) {
            this.loading = false;
            this.searchResult = [];
            this.showSearchResult = true;
            this.total = 0;
            return;
          }
          if (init) {
            this.loading = false;
            if (res.ok) {
              this.searchResult = res.data.list;
              this.total = res.data.total;
            }
          } else {
            this.loadingMore = false;
            if (res.ok) {
              this.searchResult = [...this.searchResult, ...res.data.list];
              this.total = res.data.total;
            }
          }
        })
        .catch(() => (this.loading = false));
    },

    // 处理下拉加载更多
    handleLoadMore() {
      if (this.hasMore) {
        this.fetchBook(false);
        this.showBackTop = true;
      }
    },

    handleInputConfirm() {
      this.fetchBook(true);
    },

    // 处理历史
    handleSelectHistory(keyword) {
      this.keyword = keyword;
    },

    // 处理返回顶部
    goBackTop() {
      this.scrollTop = 1;
      this.$nextTick(function () {
        this.scrollTop = 0;
      });
    },

    // 高亮关键字
    drawCorrelativeKeyword(text) {
      return `<text>${text.replace(
        this.keyword,
        `<text style='color: #4990e2;'>${this.keyword}</text>`
      )}</text>`;
    },

    // 顶置关键字
    setkeyword(data) {
      this.inputFocus = true;
      this.keyword = data.keyword;
    },

    // 清除历史搜索
    oldDelete() {
      uni.showModal({
        content: '确定清除历史搜索记录？',
        success: (res) => {
          if (res.confirm) {
            console.log('用户点击确定');
            this.oldKeywordList = [];
            uni.removeStorage({
              key: 'OldKeys',
            });
          } else if (res.cancel) {
            console.log('用户点击取消');
          }
        },
      });
    },

    // 保存关键字到历史记录
    saveKeyword(keyword) {
      if (!keyword) return false;
      uni.getStorage({
        key: 'OldKeys',
        success: (res) => {
          const OldKeys = JSON.parse(res.data);
          const findIndex = OldKeys.indexOf(keyword);
          if (findIndex == -1) {
            OldKeys.unshift(keyword);
          } else {
            OldKeys.splice(findIndex, 1);
            OldKeys.unshift(keyword);
          }
          // 最多10个纪录
          OldKeys.length > 10 && OldKeys.pop();
          uni.setStorage({
            key: 'OldKeys',
            data: JSON.stringify(OldKeys),
          });
          this.oldKeywordList = OldKeys; // 更新历史搜索
        },
        fail: () => {
          let OldKeys = [keyword];
          uni.setStorage({
            key: 'OldKeys',
            data: JSON.stringify(OldKeys),
          });
          this.oldKeywordList = OldKeys; // 更新历史搜索
        },
      });
    },
  },
};
</script>

<style lang="scss">
.search {
  &__box {
    width: 100%;
    background-color: rgb(242, 242, 242);
    padding: 15rpx 2.5%;
    display: flex;
    justify-content: space-between;
  }

  &__input {
    width: 100%;

    &-placeholder {
      color: #9e9e9e;
      font-size: 28rpx;
    }
  }

  .input-placeholder {
    color: #9e9e9e;
    font-size: 28rpx;
    line-height: 70rpx;
  }

  &__keyword-box {
    height: calc(100vh - 110rpx);
    border-radius: 20rpx 20rpx 0 0;
    background-color: #fff;
  }

  &__keyword-list {
    height: calc(100vh - 176rpx);
    border-radius: 20rpx 20rpx 0 0;
    background-color: #fff;
  }

  &__keyword-block {
    padding: 10rpx 0;

    &-header {
      width: 94%;
      padding: 10rpx 3%;
      font-size: 27rpx;
      color: #333;
      display: flex;
      justify-content: space-between;

      image {
        width: 40rpx;
        height: 40rpx;
      }
    }

    &-item {
      width: 94%;
      padding: 3px 3%;
      display: flex;
      flex-flow: wrap;
      justify-content: flex-start;

      view {
        display: flex;
        justify-content: center;
        align-items: center;
        border-radius: 60rpx;
        padding: 0 20rpx;
        margin: 10rpx 20rpx 10rpx 0;
        height: 60rpx;
        font-size: 28rpx;
        background-color: rgb(242, 242, 242);
        color: #6b6b6b;
      }
    }
  }

  &__hide {
    display: flex;
    justify-content: center;
    font-size: 28rpx;
    color: #6b6b6b;
  }

  &__item {
    padding: 28rpx $page-row-spacing;
    overflow: hidden;
    position: relative;

    &::after {
      position: absolute;
      top: 0;
      left: 0;
      display: block;
      width: 100%;
      height: 1px;
      background: $border-color-gray;
      // transform: scaleY(0.5);
      content: ' ';
    }

    &-info {
      float: left;
      width: 100%;
      padding-left: 178rpx;
    }
  }

  &__img {
    margin-right: 28rpx;
    width: 150rpx;
    height: 218rpx;
    float: left;
    margin-left: -100%;
  }

  &__name {
    color: $font-color-normal;
    font-size: 30rpx;
    line-height: 1.5em;
  }

  &__des {
    color: $font-color-desc;
    font-size: 26rpx;
    overflow: hidden;
    text-overflow: ellipsis;
    display: -webkit-box;
    -webkit-line-clamp: 3;
    -webkit-box-orient: vertical;
    line-height: 1.4em;
    margin-top: 10rpx;
    margin-bottom: 28rpx;
  }

  &__bottom {
    display: flex;
    flex-flow: row nowrap;
    justify-content: space-between;
    align-items: center;
    color: $font-color-desc;
    font-size: 26rpx;
  }

  &__load-more {
    padding: 30rpx 0;
  }

  &__no-more {
    font-size: 24rpx;
    margin-top: 10rpx;
    color: #999;
    text-align: center;
    padding: 30rpx 0;
  }

  .icon-emptypage {
    font-size: 96rpx;
    color: #999;
    position: relative;
    bottom: 20rpx;
  }

  &__backtop {
    position: fixed;
    bottom: 60rpx;
    right: 60rpx;
    text-align: center;

    .iconfont {
      font-size: 80rpx;
      display: block;
      margin: 0 auto;
      color: #999;
      padding: 20rpx;

      &:active {
        color: #666;
      }
    }
  }
}

/* #ifndef H5 */
.search {
  &__keyword-box {
    height: calc(100vh - 110rpx);
  }

  &__keyword-list {
    height: calc(100vh - 88rpx);
  }
}
/* #endif */
</style>
